from django.shortcuts import render

# Create your views here.
from django.views import View
import json

from django.http import JsonResponse
from django_redis import get_redis_connection

from apps.users.models import User

# 用户注册
class RegisterView(View):
    """用户注册"""

    def post(self, request):
        """
        实现用户注册
        :param request: 请求对象
        :return: 注册结果

        1.接收请求
        2.提取参数
        3.验证参数
        4.数据入库
        5.状态保持(sessionredis)
        ６.返回响应

        """

        # 1.接收请求
        # body=request.body
        # dody_str=body.decode()
        # data=json.loads(dody_str)
        data=json.loads(request.body.decode())

        # 2.提取参数
        mobile=data.get('mobile')
        phonecode=data.get('phonecode')
        password=data.get('password')
        # 3.验证参数
        if not all([mobile,phonecode,password]):
            return JsonResponse({'code':400,'errmsg':'参数不全'})
        # 3.1  验证手机号
        import re
        from django import http
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '请输入正确的手机号!'})
        # try:
        #     count = User.objects.filter(mobile=mobile).count()
        #     return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})
        # except:
        #     pass
        # 3.2  验证短信验证码
        # 判断短信验证码是否正确
        # redis_conn = get_redis_connection('code')
        # sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 判断短信验证码是否过期
        # 对比用户输入的和服务端存储的短信验证码是否一致
        # if not sms_code_server:
        #     return JsonResponse({'errno': 400, 'errmsg': '短信验证码失效'})
        #
        # if phonecode != sms_code_server.decode():
        #     return JsonResponse({'errno': 400, 'errmsg': '短信验证码有误'})



        # 3.3  验证密码
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': '格式有误：请输入至少8位,数字+字母组合'})

        # ４．数据入库
        try:
            user = User.objects.create_user(mobile=mobile,
                                            username=mobile,
                                            password=password
                                            )
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '手机号已存在!'})



        # 5.状态保持(sessionredis)
        from django.contrib.auth import login
        # 参数1: request      请求对象
        # 参数2: user         用户信息
        login(request,user)

        # 返回响应
        response =JsonResponse({"errno": "0", "errmsg": "注册成功"})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response

# 用户登录
class LoginView(View):
    #　登录
    def post(self,request):
        '''
        1.接收请求数据
        2.提取数据
        3.验证参数
        4.认证登录用户
        5.状态保持
        6.要根据是否记住登录
        7.返回响应
        :param requset:
        :return:
        '''

        # 1.接收请求数据
        data=json.loads(request.body.decode())
        # 2.提取数据
        username=data.get('mobile')
        password=data.get('password')
        # 3.验证参数
        if not all([username,password]):
            return JsonResponse({'code':400,'errmsg':'参数不全'})

        # 4.认证登录用户
        from django.contrib.auth import authenticate
        # xxxxx
        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({'code':400,'errmsg':'用户名或密码不正确'})

        # 5.状态保持
        from django.contrib.auth import login
        login(request,user)

        # 6.返回响应
        response = JsonResponse({"errno": "0", "errmsg": "登录成功"})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response

    # 判断用户是否登录
    def get(self,request):
        user = request.user
        if user.is_authenticated:
            user_info = {
                "name": user.username,
                "user_id": user.id,
            }
            return JsonResponse({'errno': 0,'errmsg': '已登录','data': user_info})
        else:
            return JsonResponse({"errno": "4101", "errmsg": "未登录"})

    # 退出登录
    def delete(self,request):
        # 1.把username 的session信息删除
        from django.contrib.auth import logout
        logout(request)
        # 2. 把username 的cookie信息删除
        response = JsonResponse({"errno": "0","errmsg": "已登出"})
        response.delete_cookie('username')
        return response


# 用户中心
class UserInfoView(View):
    """用户中心"""

    def get(self, request):
        """提供个人信息界面"""
        user=request.user
        # 获取界面需要的数据,进行拼接
        info_data = {
            # 'avatar':"http://www.aijia.com/"+"user.avatar_url",
            # 'create_time':request.user.create_time,
            # 'mobile': user.mobile,
            'username': user.mobile,
            'user_id':user.id,
        }

        # 返回响应
        return JsonResponse({
            "data": info_data,
            "errmsg": "OK",
            "errno": "0"
        })




